<template>
    <div class="module6-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>电池状态监控</span>
                    <el-button type="primary" @click="openAddDialog">添加数据</el-button>
                </div>
            </template>
            
            <el-table 
                :data="tableData" 
                style="width: 100%"
                stripe
                border
            >
                <el-table-column prop="siteName" label="站点名称"  />
                <el-table-column prop="batteryCode" label="电池编号"  />
                <el-table-column prop="cycleCount" label="循环次数"  sortable />
                <el-table-column prop="batteryLevel" label="电量" >
                    <template #default="{ row }">
                        <el-progress 
                            :percentage="row.batteryLevel" 
                            :color="getBatteryLevelColor(row.batteryLevel)"
                            :stroke-width="8"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="healthValue" label="健康值" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getHealthTagType(row.healthValue)">
                            {{ row.healthValue }}%
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row, $index }">
                        <el-button type="primary" size="small" @click="editRow(row, $index)">编辑</el-button>
                        <el-button type="danger" size="small" @click="deleteRow($index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加/编辑弹框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="600px"
            @close="resetForm"
        >
            <el-form 
                ref="formRef" 
                :model="formData" 
                :rules="formRules" 
                label-width="100px"
            >
                <el-form-item label="站点名称" prop="siteName">
                    <el-input v-model="formData.siteName" placeholder="请输入站点名称" />
                </el-form-item>
                <el-form-item label="电池编号" prop="batteryCode">
                    <el-input v-model="formData.batteryCode" placeholder="请输入电池编号" />
                </el-form-item>
                <el-form-item label="循环次数" prop="cycleCount">
                    <el-input-number 
                        v-model="formData.cycleCount" 
                        :min="0" 
                        :max="9999" 
                        placeholder="请输入循环次数"
                        style="width: 90%"
                    />
                    <span class="unit-text">次</span>
                </el-form-item>
                <el-form-item label="电量" prop="batteryLevel">
                    <el-input-number 
                        v-model="formData.batteryLevel" 
                        :min="0" 
                        :max="100" 
                        placeholder="请输入电量百分比"
                        style="width: 90%"
                    />
                    <span class="unit-text">%</span>
                </el-form-item>
                <el-form-item label="健康值" prop="healthValue">
                    <el-input-number 
                        v-model="formData.healthValue" 
                        :min="0" 
                        :max="100" 
                        placeholder="请输入健康值百分比"
                        style="width: 90%"
                    />
                    <span class="unit-text">%</span>
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveData">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updateDataClassify } from '@/api/port'

// 表格数据
const tableData = ref<{
    siteName: string,
    batteryCode: string,
    cycleCount: number,
    batteryLevel: number,
    healthValue: number
}[]>([])

// 弹框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加电池数据')
const isEdit = ref(false)
const editIndex = ref(-1)

// 表单数据
const formData = reactive({
    siteName: '',
    batteryCode: '',
    cycleCount: 0,
    batteryLevel: 0,
    healthValue: 0
})

// 表单验证规则
const formRules: FormRules = {
    siteName: [
        { required: true, message: '请输入站点名称', trigger: 'blur' },
        { min: 2, max: 30, message: '站点名称长度在2-30个字符', trigger: 'blur' }
    ],
    batteryCode: [
        { required: true, message: '请输入电池编号', trigger: 'blur' },
        { min: 3, max: 20, message: '电池编号长度在3-20个字符', trigger: 'blur' }
    ],
    cycleCount: [
        { required: true, message: '请输入循环次数', trigger: 'blur' },
        { type: 'number', min: 0, max: 9999, message: '循环次数必须在0-9999之间', trigger: 'blur' }
    ],
    batteryLevel: [
        { required: true, message: '请输入电量', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '电量必须在0-100之间', trigger: 'blur' }
    ],
    healthValue: [
        { required: true, message: '请输入健康值', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '健康值必须在0-100之间', trigger: 'blur' }
    ]
}

// 表单引用
const formRef = ref<FormInstance>()

// 获取电量颜色
const getBatteryLevelColor = (level: number) => {
    if (level >= 80) return '#67c23a'
    if (level >= 50) return '#e6a23c'
    if (level >= 20) return '#f56c6c'
    return '#f56c6c'
}

// 获取健康值标签类型
const getHealthTagType = (health: number) => {
    if (health >= 90) return 'success'
    if (health >= 70) return 'warning'
    return 'danger'
}

// 打开添加弹框
const openAddDialog = () => {
    dialogTitle.value = '添加电池数据'
    isEdit.value = false
    dialogVisible.value = true
}

// 编辑行数据
const editRow = (row: any, index: number) => {
    dialogTitle.value = '编辑电池数据'
    isEdit.value = true
    editIndex.value = index
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除行数据
const deleteRow = (index: number) => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        tableData.value.splice(index, 1)
        ElMessage.success('删除成功')
        updateData()
    })
}

// 保存数据
const saveData = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 编辑模式
                Object.assign(tableData.value[editIndex.value], formData)
                ElMessage.success('修改成功')
            } else {
                // 添加模式
                tableData.value.push({ ...formData })
                ElMessage.success('添加成功')
            }
            updateData()
            dialogVisible.value = false
            resetForm()
            console.log('电池数据已保存:', formData)
        }
    })
}

const updateData = async () => {
    await updateDataClassify({
        id: 3,
        key: 'module6',
        value: tableData.value
    })
    console.log('保存配送数据配置:', tableData.value)
}

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(formData, {
        siteName: '',
        batteryCode: '',
        cycleCount: 0,
        batteryLevel: 0,
        healthValue: 0
    })
    isEdit.value = false
    editIndex.value = -1
}

// 初始化函数
const init = (module: any) => {
    console.log('Module6 初始化完成')
    if(module){
        tableData.value = module
    }
}

// 暴露初始化函数
defineExpose({
    init
})
</script>

<style scoped>
.module6-container {
    padding: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
            font-size: 16px;
            font-weight: bold;
        }
    }
    
    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
    
    .unit-text {
        margin-left: 8px;
        color: #909399;
        font-size: 14px;
    }
}
</style>